package com.zlx.store.common.util;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import net.minidev.json.JSONObject;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 短信发送工具类
 * 注意，为了安全起见已经删除accessIdKey和keyId，请使用者添加各自需要的id
 */
@Component
public class SMSUtils {

    public void sendToPhone(String phone, String msg) {
    DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",
            "L", //AccessIdKey
            "Tz"); //AccessKey Secret
    IAcsClient client = new DefaultAcsClient(profile);

    CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
    //下面这3个不要改动
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
    //接收短信的手机号码
        request.putQueryParameter("PhoneNumbers",phone);//此处写电话号码
    //短信签名名称
        request.putQueryParameter("SignName","阿里云短信测试");
    //短信模板ID
        request.putQueryParameter("TemplateCode","SMS_154950909");
    //短信模板变量对应的实际值 ${code} 中的值
    Map<String,String> param = new HashMap<>(2);
        param.put(msg, String.valueOf(new Random().nextInt(80000)+10000)); //写入的短信内容
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
    } catch (ClientException e) {
        e.printStackTrace();
    }
    }}
